package com.lemon.smartsafetynew.ui.activity.user;

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.ApplicationInfo;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafetynew.entity.User;
import com.lemon.smartsafetynew.net.services.AccountServices;
import com.lemon.smartsafetynew.ui.activity.MainNewActivity;
import com.lemon.smartsafetynew.ui.adapter.user.UserAccountChooseAdapter;
import com.lemon.smartsafetynew.util.common.AppSharePreferenceUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.constants.SafeCloudConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;
import com.lemon.smartsafetynew.util.user.UserTypeUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import kale.adapter.LemonRcvAdapter;

/**
 * 用户切换企业
 * Created by Andrew on 2017/12/21.
 */

public class UserChangeAccountActivity extends SwipeBackActivity
        implements RecyclerTClickListener<User> {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;

    private LemonRcvAdapter<User> mAdapter;
    private List<User> mDataList = new ArrayList<>();

    @Override
    public void onItemClick(User data, int position) {
        toggleUser(data);
    }

    @Override
    protected void initTitle() {
        this.setBarTitle(getString(R.string.change_organization));
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(UserChangeAccountActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_user_account_choose;
    }

    @Override
    protected void initViews() {
        super.initViews();

        initRecyclerView();
        getUsers();
    }

    /**
     * 初始化页面组件
     */
    private void initRecyclerView() {
        mAdapter = new UserAccountChooseAdapter(mDataList, this);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(UserChangeAccountActivity.this, 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(mAdapter);
    }

    private void getUsers() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("user_id", AccountUtil.getUserID());

        AccountServices
                .init()
                .getAccountUsers(params);

    }

    private void toggleUser(User user) {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("old_user_id", AccountUtil.getUserID());
        params.put("user_id", user.getUserId());

        AccountServices
                .init()
                .toggleUser(params);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_TOGGLE_ACCOUNT_USER.equals(event.getTag())) {

            /**
             * 切换企业
             */
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mHUDUtil.hidden();

                if (event.getEventResult() == Constants.Result.SUCCESS) {

                    if (event.getObj() instanceof User) {
                        User user = (User) event.getObj();

                        if (user != null) {

                            if (user.getCompanyId() != null
                                    || (user.getCompanyId() == null && ApplicationInfo.PRODUCT_SUPPORT.equals(user.getUserType()))
                                    || (UserTypeUtil.isGovType(user.getUserType()))) {
                                mHUDUtil.showDoneTip(getString(R.string.change_organization_success));
                                AppSharePreferenceUtil.getInstance().putString(SafeCloudConstants.CURRENT_USER, mGson.toJson(user));
                                //保存JPush状态
                                AccountUtil.saveJPushStatus(false);
                                Intent mIntent = new Intent(UserChangeAccountActivity.this, MainNewActivity.class);
                                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(mIntent);
                            } else {
                                mHUDUtil.showErrorTip(getString(R.string.organization_is_empty_contact_admin));
                            }

                        } else {
                            mHUDUtil.showErrorTip(getString(R.string.change_organization_failed));
                        }

                    } else {
                        mHUDUtil.showErrorTip(getString(R.string.change_organization_failed));
                    }

                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }

        } else if (KeyConstants.URL_GET_ACCOUNT_USERS.equals(event.getTag())) {

            /**
             * 获取用户组
             */
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mHUDUtil.hidden();

                if (event.getEventResult() == Constants.Result.SUCCESS) {

                    List<User> users = new ArrayList<>();
                    List<Map<String, String>> maps = (List<Map<String, String>>) event.getObj();

                    for (Map<String, String> map : maps) {
                        User user = new User();
                        user.setUserId(map.get("user_id"));
                        user.setCompanyName(map.get("company_name"));
                        users.add(user);
                    }

                    mDataList.clear();
                    mAdapter.notifyDataSetChanged();
                    mAdapter.addItems(users);

                } else {
                    mHUDUtil.showErrorTip("获取用户组失败。");
                    callFinish();
                }

            }

        }
    }


}
